<%--
  Created by IntelliJ IDEA.
  User: 86183
  Date: 2022/5/5
  Time: 20:02
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>进入店铺</title>
    <link rel="shortcut icon" href="#"/>
    <style>
        body{
            color: white;
            background-color: black;
        }
    </style>
</head>
<body>
    <div>
        <div id="picture" style="display:inline-block;">
            这是店铺的照片
        </div>
        <div  id="shopMessage" style="display:inline-block;">

        </div>
    </div>
    <div>
        <button>点单</button>
        <button id="message">评价</button>
        <button id="getTicket">领取抵用券</button>
        <input type="text" id="search" placeholder="搜索"/>
        <button id="getCollection">收藏</button>
        <button id="complaint">投诉</button>
    </div>
    <span id="selectTicket"></span>
    <div>
        <div style="margin-left: 100px">
            <span id="cost"></span>
            <button id="over" onclick="over()">买单</button>
        </div>
        <div id="foods"></div>
        <hr>
        <div id="userTickets"></div>
    </div>
</body>
<script>
    let Foods;
    let Numbers;
    let Page;
    let PageNow=1;
    let userTickets;
    function initNumbers(){
        for(let i=0;i<Numbers.length;i++){
            Numbers[i]=0;
        }
    }
    function thePage(objects){
        let page=objects.length/4;
        if(objects.length%4 == 0){return page;}
        return page+1;
    }
    function nextPage(){
        console.log(PageNow)
        console.log(Page)
        if(Page-(PageNow+1)>=0){insertFoods(Foods,++PageNow)}else{alert("这是最后一页了!")};
    }
    function beforePage(){
        if(PageNow>1){insertFoods(Foods,--PageNow)}else{alert("这是第一页了!")};
    }
    function getCookie(name) {
        if (document.cookie.length > 0) {
            let start = document.cookie.indexOf(name + "=");
            if (start != -1) {
                start = start + name.length + 1;
                let end = document.cookie.indexOf(";", start);
                if (end == -1) end = document.cookie.length;
                return decodeURI(document.cookie.substring(start, end));
            }
        }
        return null;
    }
    let params = new URLSearchParams(location.search);
    let id = params.get('shopId');
    let tickets;
    console.log(id);
    function userHasCollect(){
        let json={
            "id":getCookie("id"),
            "shopId":id,
            "mode": "collection"
        }
        console.log("json:"+JSON.stringify(json))
        let xhr=new XMLHttpRequest();
        xhr.open("post","http://localhost:80/homePage",true);
        xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
        xhr.responseType='json';
        xhr.send("json="+JSON.stringify(json));
        xhr.onreadystatechange=function(){;
            if(xhr.status==200 && xhr.readyState==4){
                let data = xhr.response;
                console.log(data);
                if(data["code"]==404){
                    console.log(data.state);
                    //添加收藏
                    document.getElementById("getCollection").onclick=function (){addCollection();}
                }else{
                    let collections=JSON.parse(data.data);
                    console.log(collections);
                    document.getElementById("getCollection").onclick=function (){
                        //alert("您已收藏该店铺!")
                        deleteCollection(collections.id);
                    }
                }
            }
        }
    }
    function deleteCollection(collectionId){
        let json={
            "id":getCookie("id"),
            "shopId":id,
            "collectionId":collectionId,
            "mode": "updateCollection"
        }
        console.log("json:"+JSON.stringify(json))
        let xhr=new XMLHttpRequest();
        xhr.open("post","http://localhost:80/homePage",true);
        xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
        xhr.responseType='json';
        xhr.send("json="+JSON.stringify(json));
        xhr.onreadystatechange=function(){
            if(xhr.status==200 && xhr.readyState==4){
                let data = xhr.response;
                console.log(data);
                if(data.code==200){
                    console.log(data.state);
                    alert("取消收藏:"+data.state);
                    window.location="IntoShop.jsp?shopId="+id;
                }else{alert(data.state)}

            }
        }
    }
    function addCollection(){
        let json={
            "userId":getCookie("id"),
            "shopId":id,
            "mode":"collection"
        }
        let xhr=new XMLHttpRequest();
        xhr.open("post","http://localhost:80/intoShop",true);
        xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
        xhr.responseType='json';
        xhr.send("json="+JSON.stringify(json));
        xhr.onreadystatechange=function(){
            if(xhr.status==200 && xhr.readyState==4){
                let data = xhr.response;
                console.log(data);
                if(data["code"]==404){
                    alert(data.state);
                }else{
                    alert(data.state);
                    window.location="IntoShop.jsp?shopId="+id;
                }
            }
        }
    }
    function getShop(){
        let json={
            "shopId":id,
            "mode":"getTheShopAndFood"
        }
        let xhr=new XMLHttpRequest();
        xhr.open("post","http://localhost:80/intoShop",true);
        xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
        xhr.send("json="+JSON.stringify(json));
        xhr.responseType='json';
        xhr.onreadystatechange=function (){
            if(xhr.status==200 && xhr.readyState==4){
                let data=xhr.response;
                console.log(data);
                if(data.code==404){
                    alert(data.state);
                }else{
                    let shopAndFood=JSON.parse(data.data);
                    console.log(shopAndFood)
                    document.getElementById("shopMessage").innerHTML=
                        '<h3>'+shopAndFood[0]["name"]+'</h3>'+
                        '<br>'+
                        '<h4>'+shopAndFood[0]["introduction"]+'</h4>'+
                        '<br>'+
                        '<h5>'+
                        shopAndFood[0]["districtName"]+shopAndFood[0]["streetName"]+
                        shopAndFood[0]["detailedAddress"]+ '</h5>';
                    let foods=shopAndFood[1];
                    document.getElementById("picture").innerHTML=
                        `<img border="0" src="http://localhost/picture/upload/`+shopAndFood[0]["picture"]+
                        `" alt="picture" width="100" height="100"></div>`;
                    console.log(foods);
                    Page=thePage(foods);
                    Foods=foods;
                    Numbers=new Array(Foods.length);
                    initNumbers();
                    insertFoods(foods,1);
                }
            }
        }
    }
    function insertFoods(foods,page){
        let count=4;
        if(Page-page<1){
            count=Foods.length-(page-1)*4;
        }
        document.getElementById("foods").innerHTML='';
        for(let i=4*(page-1);i<count+4*(page-1);i++){
            document.getElementById("foods").innerHTML+=
                `<div style="margin-top: 10px">`+
                    `<div style="display:inline-block;">`+
                `<img border="0" src="http://localhost/picture/upload/`+foods[i]["picture"]+
                `" alt="picture" width="100" height="100">`+
                    `</div>`+
                    `<text id="`+foods[i]["id"]+`" style="margin-left: 10px">`+foods[i]["name"]+`<text>`+
                    `<text id="-`+foods[i]["id"]+`" style="margin-left: 10px">`+foods[i]["price"]+` 元<text>`+
                    `<button id="delete`+foods[i]["id"]+`" name="delete" style="margin-left: 10px"` +
                    ` onclick="deleteNumber('`+i+`')">-</button>`+
                    `<input type="number" id="number`+i+`" placeholder="0" maxlength="3" onblur="clickNumberText('`+i+`')"/>`+
                    `<button id="add`+foods[i]["id"]+`" style="margin-left: 10px"`+
                    `onclick="addNumber('`+i+`')">+</button>`+
                `</div>`;
        }
        document.getElementById("foods").innerHTML+=
            '<button '+
            'onclick="beforePage()">上一页</button>'+
            '<button '+
            'onclick="nextPage()">下一页</button>';
        for(let i=4*(page-1);i<count+4*(page-1);i++){
            let number=Numbers[i];
            document.getElementById("number"+i).value=number;
        }
    }
    function deleteNumber(footFoodId){
        let number=document.getElementById("number"+footFoodId).value;
        console.log(number)
        if(number==0){return;}
        document.getElementById("number"+footFoodId).value--;
        Numbers[footFoodId]--;
        console.log(footFoodId+":"+Numbers[footFoodId])
        console.log(document.getElementById("number"+footFoodId).value)
        let cost=Cost().toFixed(2);
        document.getElementById("cost").innerHTML=cost+'  元';
    }
    function addNumber(footFoodId){
        console.log(document.getElementById("number"+footFoodId).value)
        document.getElementById("number"+footFoodId).value++;
        Numbers[footFoodId]++;
        console.log(footFoodId+":"+Numbers[footFoodId])
        console.log(document.getElementById("number"+footFoodId).value)
        let cost=Cost().toFixed(2);
        document.getElementById("cost").innerHTML=cost+' 元';
    }
    function clickNumberText(i){
        let number=document.getElementById("number"+i).value;
        if(parseFloat(number)-parseInt(number)>0){alert("份数必须为整数!");return;}
        if(parseInt(number)<0){alert("份数不能为负数!");return;}
        Numbers[i]=parseInt(number);
        let cost=Cost().toFixed(2);
        document.getElementById("cost").innerHTML=cost+'  元';
    }
    function Cost(){
        let cost=0;
        console.log(Numbers)
        for(let i=0;i<Numbers.length;i++){
            if(Numbers[i]!=0 || Numbers[i]!=NaN){
                cost+=Foods[i]["price"]*Numbers[i];
            }
        }
        return cost;
    }
    function OrdersContent(){
        let content=' ';
        for(let i=0;i<Numbers.length;i++){
            if(Numbers[i]!=0){
                content+=Foods[i]["name"]+"*"+Numbers[i]+" ";
            }
        }
        console.log(content);
        return content;
    }
    function over(){
        let cost=Cost();
        if(cost==0){alert("您未下单!");return;}
        //用户是否拥有抵用券 若有,则展示选择是否使用抵用券功能
        userHasTickets();

    }
    function userHasTickets(){
        let json={
            "id":getCookie("id"),
            "shopId":id,
            "mode":"userHasTheShopTickets"
        }
        let xhr=new XMLHttpRequest();
        xhr.open("post","http://localhost:80/intoShop",true);
        xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
        xhr.send("json="+JSON.stringify(json));
        xhr.responseType='json';
        xhr.onreadystatechange=function (){
            if(xhr.status==200 && xhr.readyState==4){
                let data=xhr.response;
                console.log(data);
                if(data.code==404){
                    console.log(data.state)
                    noTicketOver();
                }else{
                    userTickets=JSON.parse(data.data);
                    console.log(userTickets);
                    if(userTickets!=undefined){
                        chooseTickets();
                    }
                }
            }
        }
    }
    function noTicketOver(){
        let cost=Cost();
        let content=OrdersContent();
        let orders={
            "cost":cost,
            "content":content,
            "userId":getCookie("id"),
            "userName":getCookie("name"),
            "shopId":id,
            "mode":"takeOrdersNoTicket"
        }
        let xhr=new XMLHttpRequest();
        xhr.open("post","http://localhost:80/intoShop",true);
        xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
        xhr.responseType='json';
        console.log(JSON.stringify(orders));
        xhr.send("json="+JSON.stringify(orders));
        xhr.onreadystatechange=function(){
            if(xhr.status==200 && xhr.readyState==4){
                let data=xhr.response;
                console.log(data);
                if(data["code"]==404){
                    console.log(data.state)
                    alert(data.data);
                }else{
                    let json=JSON.parse(data.data);
                    console.log(json)
                    alert(data.state);
                    window.location="IntoShop.jsp?shopId="+id;
                }
            }
        }
    }
    function chooseTickets(){
        document.getElementById("userTickets").innerHTML+=
            `您有抵用券,请选择是否使用:<button id="yes" onclick="showTickets()">查看并使用</button>
            <button id="no" onclick="GoOver()">直接付款</button><br>`;
    }
    function GoOver(){
        let cost=Cost();
        console.log(cost)
        let content=OrdersContent();
        let orders={
            "cost":cost,
            "content":content,
            "userId":getCookie("id"),
            "userName":getCookie("name"),
            "shopId":id,
            "mode":"takeOrdersHasTicket",
        }
        FinallySend(orders);
    }
    function FinallySend(orders){
        let xhr=new XMLHttpRequest();
        xhr.open("post","http://localhost:80/intoShop",true);
        xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
        xhr.responseType='json';
        console.log(JSON.stringify(orders));
        xhr.send("json="+JSON.stringify(orders));
        xhr.onreadystatechange=function(){
            if(xhr.status==200 && xhr.readyState==4){
                let data=xhr.response;
                console.log(data);
                if(data["code"]==404){
                    console.log(data.state)
                    alert(data.state);
                }else{
                    let json=JSON.parse(data.data);
                    console.log(json)
                    alert(data.state);
                    window.location="IntoShop.jsp?shopId="+id;
                }
            }
        }
    }
    function showTickets(){
        document.getElementById("userTickets").innerHTML='';
        for(let i=0;i<userTickets.length;i++) {
            document.getElementById("userTickets").innerHTML +=
                '<input type="radio" name="chooseWhichTicket"' +
                ' value="'+i+'">' +
                '折扣:<text>' + userTickets[i]['discount'] + '折</text><br>' +
                '有效期:至 <text>' + userTickets[i]['deadline'] + '</text><br>' + '<hr>';
        }
        document.getElementById("userTickets").innerHTML+=
            '<button id="final" onclick="choseWhichTicket()">付款</button>'
    }
    //有也可能没有的使用抵用券时的最终付款
    function choseWhichTicket(){
        let obj=document.getElementsByName("chooseWhichTicket")
        let ticketFoot=-1;
        for(let i=0;i<obj.length;i++){
            if(obj[i].checked){
                console.log(obj[i].value);//OK ticket of foot
                ticketFoot=obj[i].value;
            }
        }
        console.log(ticketFoot)
        let cost=Cost();
        console.log(cost)
        let content=OrdersContent();
        let orders={
            "cost":cost,
            "content":content,
            "userId":getCookie("id"),
            "userName":getCookie("name"),
            "shopId":id,
            "mode":"takeOrdersNoTicket",
        }
        if(ticketFoot>=0){
            cost=(cost*userTickets[ticketFoot]["discount"]/10);
            orders={
                "cost":cost,
                "content":content,
                "userId":getCookie("id"),
                "userName":getCookie("name"),
                "shopId":id,
                "mode":"takeOrdersHasTicket",
                "ticketId":userTickets[ticketFoot]["id"]
            }
        }
        FinallySend(orders);
    }
    getShop();
    document.getElementById("complaint").onclick=function (){
        window.location="Complaint.jsp";
    }
    function HasTickets (){
        let sendTicket={
            "shopId":id,
            "mode":"hasTicket"
        }
        let xhr=new XMLHttpRequest();
        xhr.open("post","http://localhost:80/ticket",true);
        xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
        xhr.responseType='json';
        xhr.send("json="+JSON.stringify(sendTicket));
        xhr.onreadystatechange=function(){
            if(xhr.status==200 && xhr.readyState==4){
                let data = xhr.response;
                console.log(data);
                if(data["code"]==404){
                    document.getElementById("getTicket").style.display='none';
                }else{
                    tickets=JSON.parse(data.data);
                    console.log(JSON.parse(data.data));
                    document.getElementById("getTicket").style.display="block";
                }
            }
        }
    }
    HasTickets();
    userHasCollect();
    document.getElementById("getTicket").onclick=function (){
        if(tickets!=''){
            document.getElementById("selectTicket").innerHTML='';
            for(let i=0;i<tickets.length;i++){
                if(tickets[i]["number"]!=0){
                    document.getElementById("selectTicket").innerHTML+=
                        '<input type="radio" name="tickets" value="'+
                        tickets[i]["discount"]+'"/>'+tickets[i]["discount"]+' 折';
                }
            }
            document.getElementById("selectTicket").innerHTML+=
                '<button id="get">领取</button>';
            document.getElementById("get").onclick=function (){
                let tickets=document.getElementsByName("tickets");
                for(let i=0;i<tickets.length;i++){
                    if(tickets[i].checked){
                        console.log(tickets[i].value)
                        let sendTicket={
                            "shopId":id,
                            "mode":"getTicket",
                            "折扣":tickets[i].value,
                            "id":getCookie("id")
                        }
                        console.log(JSON.stringify(sendTicket));
                        let xhr=new XMLHttpRequest();
                        xhr.open("post","http://localhost:80/ticket",true);
                        xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
                        xhr.responseType='json';
                        xhr.send("json="+JSON.stringify(sendTicket));
                        xhr.onreadystatechange=function(){
                            if(xhr.status==200 && xhr.readyState==4){
                                let data = xhr.response;
                                console.log(data);
                                if(data["code"]==404){
                                    console.log(data.state);
                                }else{
                                    console.log(JSON.parse(data.data));
                                    alert(data.state);
                                    window.location="IntoShop.jsp?shopId="+id;
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    document.getElementById("message").onclick=function (){
        window.location="Message.jsp?shopId="+id;
    }
</script>
</html>
